package com.ipartek.formacion.gestformwww.controlador;

import com.ipartek.formacion.gestformwww.modelo.ModeloModulo;
import com.ipartek.formacion.gestformwww.modelo.beans.Modulo;
import com.ipartek.formacion.gestformwww.modelo.beans.excepciones.GestorFormacionExcepcion;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Karmele y Victor
 */
public class CrearModuloAccion implements Accion {

   
    private String visualizarcurso = "visualizar-curso-accion";

    public AccionRouter ejecuta(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) {
        AccionRouter router = null;
         AccionServlet as=(AccionServlet) servlet;
        HttpSession sesion = request.getSession();
        ModeloModulo modelo = (ModeloModulo) servlet.getServletContext().getAttribute("ModeloModulo");
        Modulo modulo = new Modulo();
        ArrayList<String> errores = null;

        if (sesion.getAttribute("usuario") == null) {
            router = new AccionRouter("inicio", false);
        } else {
            if (request.getMethod().equalsIgnoreCase("POST")) {
                modulo.setModDescr(request.getParameter("ModDescr"));
                modulo.setModDuracion(request.getParameter("ModDur"));
                modulo.setCurId(request.getParameter("idCurso"));
                errores = modulo.validar();
                if (!errores.isEmpty()) {
                    request.setAttribute("erroresmodulo", errores);
                } else if (Verificador.sinReenvio("aleatorioCrearModulo", sesion, request)) {
                    try {
                        modelo.crearModulo(modulo);
                    } catch (GestorFormacionExcepcion ex) {
                        Logger.getLogger(CrearModuloAccion.class.getName()).log(Level.SEVERE, null, ex);
                        errores.add(ex.getMessage());
                        request.setAttribute("erroresmodulo", errores);
                    }
                }
            }
            try {
                router=as.getFactory().getAction(as.getNombreClaseRecurso(visualizarcurso),servlet.getClass().getClassLoader()).ejecuta(servlet, request, response);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(CrearModuloAccion.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(CrearModuloAccion.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(CrearModuloAccion.class.getName()).log(Level.SEVERE, null, ex);
            }
          
        }
        return router;
    }

    
}
